var BASE_URL = 'https://gconnect-dev.iserviceglobe.net/';
var SYNC_URL = 'gmail/sync_email/';
var matches = google.contentmatch.getContentMatches();
var message_id = matches[0]['message_id']
//var recipient_email = matches[1]['recipient_email']
var userEmail = ""
var prefs = new gadgets.Prefs();
console.log("message id",message_id);
//console.log("recipent email",recipient_email);

function main(){
      gadgets.window.adjustHeight(0);
      window.innerHeight = 0;
      var status = prefs.getString("status");
      var email_sync = prefs.getString("email_sync");
      var lastcheckdate = new Date(prefs.getString("date"));
      var now = new Date();
      userEmail = prefs.getString("email");
      if ( (((now.getTime() - lastcheckdate.getTime())) >= 14400000) || lastcheckdate == "Invalid Date" ){
          osapi.http.get({
          'href' : BASE_URL+SYNC_URL,
          'format' : 'json',
          'authz' : 'signed'
        }).execute(handleLoadResponse);
      }
      
      
    if(status == "true" && email_sync == "true"){
       gadgets.window.setTitle("G-Connect");
       $('body').show();
       $('body').css("display","block");
       $('#sync_email').show();
       gadgets.window.adjustHeight(70);
    }
      

    $('#sync_email').click(syncEmail);
    $('#spinner').hide();
    //fetchData();
}

function handleLoadResponse(data) {
      // User exists, OpenID must have occurred previously.
      var date = new Date();
      prefs.set("date",date.toString());
      if (data.content.user_exists && data.content.email_sync) {
        console.log(data.content.user_exists);
        prefs.set("status","true");
        prefs.set("email_sync", "true");
        prefs.set("email",data.content.email);
        userEmail = prefs.getString("email");
        gadgets.window.setTitle("G-Connect");
        $('body').show();
        $('body').css("display","block");
        $('#sync_email').show();
        gadgets.window.adjustHeight(70);
      // User doesn't exist, need to do OpenID to match user ID to OpenID.
      }else{
        prefs.set("status","false");
        prefs.set("email_sync", "false");
        $('#sync_email').hide();
        gadgets.window.adjustHeight(0);
      }
    }




function syncEmail(){
  $('#sync_email').prop("disabled",true);
  $('#spinner').show();
  $('li.emailerror').remove();

  if (userEmail == ""){
    main();
    //fetchData(nextStep);
  }
  else{
    nextStep();
    }
}

function nextStep(){
   var url = BASE_URL+SYNC_URL;
   var params = {};
   var data =  $.param({"message_id": message_id, 
                        "email": userEmail});
   params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
   params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
   params[gadgets.io.RequestParameters.POST_DATA] = data;

/*   $.post(url,{"message_id":message_id,"email":userEmail}).done(function(resp){
    color= "red"
    if (resp=="Synced Sucessfully.."){
      color = "green"
    }
    $("#resp").append("<li class='emailerror' style='color:"+color+"; list-style:none;font-weight:bold;margin-top:4px;'>"+resp+"</li>");
    $('#spinner').hide();
    $('#sync_email').prop("disabled",false);
    console.log("response:",resp);
  }).fail(function(resp){
    var resp = "Failed ,Try Again..";
    $("#resp").append("<li class='emailerror' style='color:red; list-style:none;font-weight:bold;margin-top:4px;'>"+resp+"</li>");
    $('#spinner').hide();
    $('#sync_email').prop("disabled",false);
    console.log("response:",resp);
  });*/
  
  gadgets.io.makeRequest(url, response, params);
  
      function response(obj){
        if (obj.text){
            var color= "red";
            if (obj.text=="Synced Sucessfully.."){
                color= "green";
            }
            $('#resp').show();
            $("#resp").append("<li class='emailerror' style='color:"+color+";list-style:none;font-weight:bold;margin-top:4px;'>"+obj.text+"</li>");
            $('#spinner').hide();
            $('#sync_email').prop("disabled",false);
            console.log("response:",obj.text);
        }
       else if(obj.error){
           var resp = "Failed ,Try Again..";
           $('#resp').show();
           $("#resp").append("<li class='emailerror' style='color:red; list-style:none;font-weight:bold;margin-top:4px;'>"+resp+"</li>");
           $('#spinner').hide();
           $('#sync_email').prop("disabled",false);
           console.log("response:",resp);
       }
    }
}


gadgets.util.registerOnLoadHandler(main);
gadgets.window.adjustHeight(0);
